package com.glowdayz.glowmee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.glowdayz.common.ImageDownloader;
import com.glowdayz.common.XmlParser;
import com.glowdayz.model.ProductCMD;
import com.glowdayz.model.UserInfo;



public class ProfileWishFm extends ScrollTabHolderFragment implements OnScrollListener, OnItemClickListener {
	
	private static final String ARG_POSITION = "position";
	private int mPosition;
	
	ListView productList = null;
	ArrayList<ProductCMD> list = null;
	DataAdapter adapter = null;
	
	// Footer 레이아웃
	LinearLayout llFooter = null;
	
	/********** 페이지 구현 **********/
	private int page = 1;						// 현재 페이지
	private final static int pageSize = 20;		// 한 페이지에 보일 수
	private int totalCount = 0;					// 전체 게시물 수
	
	TextView wishCount = null;
	
	int idRegister = 0;
	
	String url = null;
	
	public static Fragment newInstance(int position, int id) {
		ProfileWishFm f = new ProfileWishFm();
		Bundle b = new Bundle();
		b.putInt(ARG_POSITION, position);
		b.putInt("idRegister", id);
		f.setArguments(b);
		return f;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View productView = inflater.inflate(R.layout.fm_search_product, container, false);
		
		mPosition = getArguments().getInt(ARG_POSITION);
		idRegister = getArguments().getInt("idRegister");
		
		productList = (ListView) productView.findViewById(R.id.searchProductList);
        
        // 메인 디지안과 별도로 레이아웃을 불러오기
		LayoutInflater li = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		llFooter = (LinearLayout) li.inflate(R.layout.list_footer, null);
		llFooter.setVisibility(View.GONE);
		// 리스트뷰에 추가
		productList.addFooterView(llFooter);
		productList.setOnScrollListener(this);
		
		View placeHolderView = inflater.inflate(R.layout.view_header_placeholder, productList, false);
		productList.addHeaderView(placeHolderView);
        
        list = new ArrayList<ProductCMD>();
		adapter = new DataAdapter(getActivity(), list);
		productList.setAdapter(adapter);
		productList.setOnItemClickListener(this);
		
		productList.setSelector(android.R.color.transparent);
		
		wishCount = (TextView) getActivity().findViewById(R.id.count);
		
		if (mPosition == 2) {
			if (idRegister < 1) {
				idRegister = UserInfo.getInstance().getUSER_ID();
			}
			
			url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
					"page=" + page + "&count=" + pageSize + "&type=wish" + "&id=" + idRegister;
			(new ProductListWorker()).execute();
		}
 
        return productView;
	}
	
	public class DataAdapter extends ArrayAdapter<ProductCMD> {
		private LayoutInflater inflater = null;

		// 생성자. 파라미터에 전달되는 List의 제너릭스 선언에 주의한다.
		public DataAdapter(Context context, List<ProductCMD> objects) {
			super(context, 0, objects);
			inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		// ArrayList에 할당된 각 항목을 하나씩 추출하여 list_item.xml에 표현시키는 메서드
		// 이 메서드는 ListView에 의해서 호출된다.
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			/** 모든 컴포넌트의 최상위 클래스 */
			View view = null;

			// 데이터를 저장할 View 선언. view 객체는 "list_item.xml"파일을 의미한다.
			if (convertView == null) {
				view = inflater.inflate(R.layout.list_product_item, null);
			} else {
				view = convertView;
			}

			// 하나의 데이터 항목을 추출한다.
			ProductCMD item = getItem(position);

			// 추출한 데이터가 존재한다면 "list_item.xml"안의 컨트롤들을 추출하여 처리한다.
			if (item != null) {
				ImageView productImg = (ImageView) view.findViewById(R.id.productImg);
				ImageView brandImg = (ImageView) view.findViewById(R.id.brandImg);
				
				TextView productTitle = (TextView) view.findViewById(R.id.productTitle);
				TextView productVolume = (TextView) view.findViewById(R.id.productVolume);
				TextView productPrice = (TextView) view.findViewById(R.id.productPrice);
				TextView productRating = (TextView) view.findViewById(R.id.productRating);
				
				RatingBar productRatingBar = (RatingBar) view.findViewById(R.id.productRatingBar);
				productRatingBar.setFocusable(false);
				productRatingBar.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						return true;
					}
				});
				productRatingBar.setStepSize((float) 0.1);
				productRatingBar.setRating(Float.parseFloat(String.valueOf(item.getRatingAvg())));
				
				productTitle.setText(item.getProductTitle());
				productVolume.setText(item.getVolume());
				productPrice.setText(String.valueOf(item.getPrice()));
				productRating.setText(String.valueOf(item.getRatingAvg()));
				
				ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getCreate_date().trim(), productImg);
				ImageDownloader.getInstance().download(getResources().getString(R.string.server_url) + item.getImage().trim(), brandImg);
				
				view.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent arg1) {
						v.setBackgroundResource(android.R.drawable.list_selector_background);
						return false;
					}
				});
			}
			return view;
		}
	}
	
	public class ProductListWorker extends AsyncTask<Object, ProductCMD, Object> {
		@Override
		protected void onPreExecute() {
			llFooter.setVisibility(View.VISIBLE);
		}

		@Override
		protected synchronized Object doInBackground(Object... params) {
			
			Object result = null;
			
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			try {
				String tag = null;
				int type = parser.getEventType();

				/** 읽은 내용을 담기 위한 변수 */
				int idProduct = 0;
				String productTitle = null;
				int idBrand = 0;
				String idBrandValue = null;
				String volume = null;
				int price = 0;
				double ratingAvg = 0.0;
				int rationCount = 0;
				String image = null;
				String productImg = null;
				
				
				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							totalCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idProduct")) {
							parser.next();
							idProduct = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("productTitle")) {
							parser.next();
							productTitle = parser.getText();
						} else if (tag.equals("idBrand")) {
							parser.next();
							idBrand = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("idBrandValue")) {
							parser.next();
							idBrandValue = parser.getText();
						} else if (tag.equals("volume")) {
							parser.next();
							volume = parser.getText();
						} else if (tag.equals("price")) {
							parser.next();
							price = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("ratingAvg")) {
							parser.next();
							ratingAvg = Double.parseDouble(parser.getText().trim());
						} else if (tag.equals("rationCount")) {
							parser.next();
							rationCount = Integer.parseInt(parser.getText().trim());
						} else if (tag.equals("brandThumbnail")) {
							parser.next();
							image = parser.getText();
						} else if (tag.equals("productThumbnail")) {
							parser.next();
							productImg = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						
						if (tag.equals("item")) {
							ProductCMD item = new ProductCMD(
									idProduct, idBrand, idBrandValue, productTitle, volume, price, ratingAvg, rationCount, image, productImg);
							publishProgress(item);
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(ProductCMD... param) {
			adapter.add(param[0]);
		}

		@Override
		protected void onPostExecute(Object param) {
			llFooter.setVisibility(View.GONE);
		}
		
		@Override
		protected void onCancelled() {
			llFooter.setVisibility(View.GONE);
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new ProductListWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getActivity().finish();
				}
			});
			alert.create();
			alert.show();
		}
	}
	
	// 화면에 리스트의 마지막 아이템이 보여지는 체크
	boolean lastItemVisibleFlag = false;

	@Override
	public void adjustScroll(int scrollHeight) {
		wishCount.setText(totalCount + " wishes");
		if (scrollHeight == 0 && productList.getFirstVisiblePosition() >= 1) {
			return;
		}
		productList.setSelectionFromTop(1, scrollHeight);
		
		FrameLayout addLayout = (FrameLayout) getActivity().findViewById(R.id.addLayout);
		if (totalCount == 0) {
			ImageView textImg = (ImageView) getActivity().findViewById(R.id.textImg);
			textImg.setImageResource(R.drawable.profile_text3);
			ImageView btImg = (ImageView) getActivity().findViewById(R.id.btImg);
			btImg.setImageResource(R.drawable.profile_bt3);
			btImg.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(getActivity(), Index.class);
					intent.putExtra("PARAM_type", "product");
					startActivity(intent);
				}
			});
			addLayout.setVisibility(View.VISIBLE);
		} else {
			addLayout.setVisibility(View.GONE);
		}

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		lastItemVisibleFlag = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount);
		if (mScrollTabHolder != null)
			mScrollTabHolder.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount, mPosition);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && lastItemVisibleFlag) {
			int pageCount = ((totalCount -1) / pageSize) + 1;
			if (pageCount > 0 && page < pageCount) {
				page++;
				url = getResources().getString(R.string.server_url) + "/glowmee/listProductXml.do?" +
						"page=" + page + "&count=" + pageSize + "&type=wish" + "&id=" + idRegister;
				(new ProductListWorker()).execute();
			}
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg2 > 0) {
			ProductCMD select = adapter.getItem(arg2 - 1);
			int id = select.getIdProduct();
			String title = select.getProductTitle();
			Intent intent = new Intent(getActivity(), ViewProduct.class);
			intent.putExtra("PARAM_id", id);
			intent.putExtra("PARAM_title", title);
			startActivity(intent);
		}
	}

}
